<?php

namespace app\api\controller;

use app\api\model\ConfigPersonal;
use app\api\model\ConfigPrice;
use app\api\model\GradeCharm;
use app\api\model\Privatechat;
use think\Db;
use think\Validate;
use think\Cache;

class Personal extends Common
{
    // 推送展示列表
    public function pushLists()
    {
        $user_id = input('user_id/d');

        $contain = [
            $tid = input('tid/d') ? input('tid/d') : 0,
        ];

        // 开始验证
        $validate = new Validate([
            ['tid', '>=:0', '操作有误'],
        ]);

        if (!$validate->check($contain)) {
            exit(json_encode(['code' => 400, 'msg' => $validate->getError()]));
        } else {
            $where = [];
            if ($tid) {
                $where['tid'] = $tid;
            }

            $where['is_hidden'] = 0;

            $data = Db::name('push_category')->field('id ,tid ,title')->where($where)->order('sort desc, id asc')->select();

            $contain = [];
            foreach ($data as $k => $v) {
                $contain[] = $v['id'];
            }

            $pushs = Db::name('push_member')->where(['user_id' => $user_id, 'cid' => ['in', $contain]])->column('id, cid');

            $contain = [];
            foreach ($data as $k => $v) {
                $contain[$v['id']] = $k;
            }

            foreach ($data as $k => $v) {
                if (empty($pushs) || !in_array($v['id'], $pushs)) {
                    $v['enable'] = 0;
                } else {
                    $v['enable'] = 1;
                }

                $v['child'] = [];

                if (isset($contain[$v['tid']])) {
                    $data[$contain[$v['tid']]]['child'][] = $v;

                    unset($data[$k]);
                } else {
                    $data[$k] = $v;
                }
            }

            return json(['code' => 200, 'data' => $data]);
        }
    }

    // 推送设置
    public function pushSet()
    {
        $user_id = input('user_id/d');

        $contain = [
            'id' => $id = input('id/d'),
        ];

        // 开始验证
        $validate = new Validate([
            ['id', 'require|>:0', '操作有误|操作有误'],
        ]);

        if (!$validate->check($contain)) {
            exit(json_encode(['code' => 400, 'msg' => $validate->getError()]));
        } else {

            $res = Db::name('push_category')->where('id', $id)->find();

            if ($res) {
                if (!$res['tid']) { // 总开关
                    $result = Db::name('push_member')->where(['cid' => $id, 'user_id' => $user_id])->find();
                    if ($result) {
                        Db::name('push_member')->where('user_id', $user_id)->delete();
                    } else {
                        $ids = Db::name('push_category')->where(['is_hidden' => 0])->column('id');
                        $con = [];
                        foreach ($ids as $k => $v) {
                            $con[] = ['cid' => $v, 'user_id' => $user_id];
                        }
                        if ($con) {
                            Db::name('push_member')->insertAll($con);
                        }
                    }
                } else {
                    $result = Db::name('push_category')->where('id', $res['tid'])->find();
                    if (!$result) return json(['code' => 400, 'msg' => '操作出错']);

                    $result = Db::name('push_member')->where(['cid' => $res['id'], 'user_id' => $user_id])->find();
                    if ($result) {
                        Db::name('push_member')->where('id', $result['id'])->delete();
                    } else {
                        Db::name('push_member')->insert(['cid' => $res['id'], 'user_id' => $user_id]);
                    }
                }
            } else {
                return json(['code' => 400, 'msg' => '操作有误']);
            }

            return json(['code' => 200, 'msg' => 'success']);
        }
    }

    public function config()
    {
        $data = ConfigPersonal::get(['user_id' => $this->params['user_id']]);

        return $this->pass($data);
    }

    public function editConfig()
    {
        $userInfo = Db::name('user')->find($this->params['user_id']);
        // if ($userInfo['age'] < 18) {
        //     return $this->miss('未成年不可设置付费');
        // }
        $config = Db::name('config_system')->where(['title'=>['in', ['edit_config_auth', 'chat_set_price_not']]])->column('content', 'title');

        if ($config['chat_set_price_not']) {
            if (in_array($this->member['id'], explode(',', $config['chat_set_price_not']))){
                return $this->miss('设置失败,请稍后再试');
            }
        }

        $chat_set_price_not = Db::name('limit_change_price_config')->where(['user_id'=>$this->params['user_id']])->find();
        if ($chat_set_price_not) {
            return $this->miss('设置失败,请稍后再试');
        }

        if ($config['edit_config_auth']) {
            if (!in_array($this->member['realname_auth'], [1,2])){
                return $this->miss('请先完成实名', 403);
            }
        }
        // $limitdatetime = '2023-04-15 00:00:00';
        // $limittime = strtotime($limitdatetime);
        // if (strtotime($this->member['register_datetime']) >= $limittime) {
        //     $hasAuth = Db::connect('database9')->name('user_attestation')->where(['user_id'=>$this->member['id'], 'types'=>2])->find();
        //     if (!$hasAuth) {
        //         return $this->miss('经验认证通过后才可调整收费');
        //     }
        // }

        $data = ConfigPersonal::get(['user_id' => $this->params['user_id']]);
        $old_value = 0;
        $price_key = ['chat_price', 'voice_price', 'video_price'];
        $price_idx = 0;
        $new_value = 0;
        if (isset($this->params['chat_price'])) {
            $price_idx = 0;
            $new_value = $this->params['chat_price'];
        } else if (isset($this->params['voice_price'])) {
            $price_idx = 1;
            $new_value = $this->params['voice_price'];
        } else if (isset($this->params['video_price'])) {
            $price_idx = 2;
            $new_value = $this->params['video_price'];
        }

        if ($new_value) {
            if (!$data['chat_rule_agree']) {
                // return $this->miss('请先阅读并同意聊天协议');
            }
        }

        if ($new_value) {
            $old_value = $data ? $data[$price_key[$price_idx]] : 0;
            if ($new_value != $old_value) {
                $todayChangeCount = Db::name('user_chat_price_records')->where([
                    'user_id'   =>  $this->member['id'],
                    'type'      =>  $price_idx,
                ])->whereTime('time', 'today')->count();
                // if ($todayChangeCount >= 2) {
                //     return $this->miss('今日修改价格次数已达上限');
                // }
                Db::name('user_chat_price_records')->insert([
                    'user_id'   =>  $this->member['id'],
                    'type'      =>  $price_idx,
                    'old_value' =>  $old_value,
                    'new_value' =>  $new_value,
                    'time'      =>  time()
                ]);
            }
        }

        if (isset($this->params['voice_switch']) && $this->params['voice_switch'] == 0) {
            Privatechat::notice($this->member['id'], '您主动关闭了接收语音通话请求,后续将不再收到其他用户向你拨出的语音通话,如需修改,请前往隐私设置关闭 拒绝语音通话请求', '', 0, 0);
        } else if (isset($this->params['video_switch']) && $this->params['video_switch'] == 0) {
            Privatechat::notice($this->member['id'], '您主动关闭了接收视频通话请求,后续将不再收到其他用户向你拨出的视频通话,如需修改,请前往隐私设置关闭 拒绝视频通话请求', '', 0, 0);
        }
        //file_put_contents('./log.txt', json_encode($this->params), FILE_APPEND);
        if ($data) {
            ConfigPersonal::where(['user_id' => $this->params['user_id']])->update($this->params);
            // if(isset($this->params['hide_distance'])){
            //     Db::name('user')->where(['id'=> $this->params['user_id']])->update(['hide_distance'=> $this->params['hide_distance']]);
            // }
            if(isset($this->params['is_hide'])){
                Db::name('user')->where(['id'=> $this->params['user_id']])->update(['is_hide'=> $this->params['is_hide']]);
            }
            
            if ($userInfo['sex'] =='女'){
               if(isset($this->params['hide_distance'])){
                    Db::name('user')->where(['id'=> $this->params['user_id']])->update(['hide_distance'=> $this->params['hide_distance']]);
                }
               
                $searchUserCacheKey = 'searchUser:'.$this->params['user_id'].':0:0:10';
                $userCacheDate = cache($searchUserCacheKey);
                if ($userCacheDate && is_array($userCacheDate)) {
                    $userCacheDate[0]['hide_distance'] = $this->params['hide_distance'];
                    //file_put_contents('./log.txt', json_encode($userCacheDate), FILE_APPEND);
                    cache($searchUserCacheKey, $userCacheDate, 5);//更新缓存
                    //file_put_contents('./log.txt', json_encode($userCacheDate), FILE_APPEND);
                }
            }
            
            // $searchUserCacheKey = 'searchUser:'.$this->params['user_id'].':0:0:10';
            // $userCacheDate = cache($searchUserCacheKey);
            // if ($userCacheDate && is_array($userCacheDate)) {
            //     $userCacheDate[0]['hide_distance'] = $this->params['hide_distance'];
            //     //file_put_contents('./log.txt', json_encode($userCacheDate), FILE_APPEND);
            //     cache($searchUserCacheKey, $userCacheDate, 5);//更新缓存
            //     //file_put_contents('./log.txt', json_encode($userCacheDate), FILE_APPEND);
            // }
            //file_put_contents('./log.txt', json_encode(ConfigPersonal::getLastSql()), FILE_APPEND);
        } else {
            $sex = $this->member['sex'] == '男' ? '男' : '女';

            $response = ConfigPersonal::createData($this->params['user_id'], $sex);
            $result = $response->getData();
            if ($result['code'] == 400) {
                return $response;
            }

            ConfigPersonal::where(['user_id' => $this->params['user_id']])->update($this->params);
        }

        // if ($this->member['sex'] == '女' && isset($this->params['video_price']) && $this->params['video_price'] > 0 && (!$data || $data['video_price'] == 0)) {
            // action('api/Login/systemPushLianmaiFemale');
        // }

        return $this->return['common.success.update'];
    }

    public function rechargeList()
    {
        //$data = ConfigPrice::all(['types' => $this->params['types']]);

        $types = $this->params['types'];

        $data = ConfigPrice::all(function($query) use ($types) {
            $query->where(['types' => $types])->order('price', 'asc');
        });

        $types = $this->member['sex'] == '男' ? 1 : 2;

        $grade = GradeCharm::where(['types' => $types, 'min' => ['elt', $this->member['charm_value']]])->order('grade desc')->value('grade');

        // $hasAttestation = Db::name('user_attestation')->where(['types'=>['<=',5],'user_id'=>$this->member['id'], 'status'=>1])->count();
        $unset = true;
        foreach ($data as $key => $item) {
            //$data[$key]['allow'] = $grade >= $item['min_charm_grade'] ? 1 : 0;
            $data[$key]['allow'] = 1;
            if ($this->member['entertainment'] == 2 || $this->member['entertainment'] == 3) $data[$key]['price'] = number_format($data[$key]['price'] * 0.2, 2);
            // if ($hasAttestation && $unset) {
            //     if ($data[$key]['allow'] == 0) {
            //         $unset = false;
            //         $data[$key]['allow'] = 1;
            //         $data[$key]['min_charm_grade'] = 0;
            //     }
            // }
        }

        return $this->pass($data);
    }

    public function level()
    {
        $types = $this->member['sex'] == '男' ? 1 : 2;

        $grade = GradeCharm::where(['types' => $types])->field('id,name,icon,min')->order('grade asc')->select();

        foreach ($grade as &$item) {
            $item['reach'] = false;
            $item['min'] = floatval($item['min']);
            if ($item['min'] <= $this->member['charm_value']) {
                $item['reach'] = true;
            }
        }

        $rule = [
            '收益1积分可增加1魅力值',
            '发一篇动态可增加10魅力值',
            '被点赞一次可增加1魅力值',
            '被浏览一次可增加0.01魅力值',
            '被收藏一次可增加5魅力值',
            '被评论一次可增加2魅力值',
        ];

        return $this->pass($grade, 'data', compact('rule'));
    }

    public function checkSwitch(): \think\response\Json
    {
        $status = 0;

        if ($this->member['sex'] == '男' && $this->member['yqr']) {
            $parent = Db::name('user')->field('sex')->where(['yqm' => $this->member['yqr']])->cache(86400)->find();
            if ($parent && $parent['sex'] != $this->member['sex']) {
                $status = 1;
            }
        }

        return $this->pass(['hide_search' => $status]);
    }
}
